package ge.telasi.tasks.ui.search;

import ge.telasi.tasks.model.Structure;
import ge.telasi.tasks.ui.UIUtils;
import ge.telasi.tasks.ui.comp.CommonDialog;
import ge.telasi.tasks.ui.comp.TableModel;
import ge.telasi.tasks.ui.structure.StructureSelectDialog;
import ge.telasi.tasks.ui.structure.StructureTable;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * Date search.
 *
 * @author dimitri
 */
public class StructureSearch extends JPanel implements FieldEditor<StructureField> {
    private static final long serialVersionUID = 968234550904462309L;
    private StructureField proto;
    private JTextField text;
    private JButton button;
    private List<Structure> structures = new ArrayList<Structure>();

    public StructureSearch() {
        initComponents();
        resetText();
    }

    private void initComponents() {
        setLayout(new BorderLayout(5, 5));
        text = new JTextField();
        text.setEditable(false);
        text.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                resetText();
            }
        });
        button = new JButton("...");
        button.setToolTipText("შეცვლა");
        add(text, BorderLayout.CENTER);
        add(button, BorderLayout.EAST);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UserListEditor dialog = new UserListEditor();
                UIUtils.openDialog(dialog);
            }
        });
    }

    public StructureField getField() {
        StructureField field = new StructureField(proto.getName(), proto.getHumanName());
        field.setStructures(structures);
        return field;
    }

    public void setField(StructureField field) {
        this.proto = field;
    }

    private void resetText() {
        if (!structures.isEmpty()) {
            String fullText = getFullText();
            int width = text.getSize().width;
            int textWidth = text.getFontMetrics(text.getFont()).stringWidth(fullText);
            if (textWidth <= width) {
                text.setText(fullText);
            } else {
                text.setText(structures.size() + " სტრუქტ. ერთეული");
            }
        } else {
            text.setText("(ცარიელი)");
        }
    }

    private String getFullText() {
        StringBuilder b = new StringBuilder();
        boolean first = true;
        for (Structure structure : structures) {
            if (!first) {
                b.append(", ");
            }
            b.append(structure.getName());
            first = false;
        }
        return b.toString();
    }

    /**
     * Structure list editor.
     */
    private class UserListEditor extends CommonDialog {
        private static final long serialVersionUID = -5847498605376568941L;
        private StructureTable userTable;
        private JButton btnAdd;
        private JButton btnRemove;
        private JButton closeButton;

        public UserListEditor() {
            super(StructureSearch.this, true);
            initComponents();
            getRootPane().setDefaultButton(closeButton);
            setSize(new Dimension(500, 300));
            setTitle(proto.getHumanName());
            userTable.setStructures(structures);
            enableComponents();
        }

        private void initComponents() {
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(centerPanel(), BorderLayout.CENTER);
            getContentPane().add(bottomPanel(), BorderLayout.SOUTH);
        }

        private Component centerPanel() {
            JPanel panel = new JPanel(new BorderLayout());
            userTable = new StructureTable();
            userTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            userTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    enableComponents();
                }
            });
            panel.add(new JScrollPane(userTable));
            JToolBar toolBar = new JToolBar();
            toolBar.setFloatable(false);
            btnAdd = new JButton();
            btnRemove = new JButton();
            btnAdd.setIcon(UIUtils.getIcon16x16("add.png"));
            btnRemove.setIcon(UIUtils.getIcon16x16("delete.png"));
            btnAdd.setToolTipText("დამატება");
            btnRemove.setToolTipText("წაშლა");
            btnAdd.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    StructureSelectDialog dialog = new StructureSelectDialog(StructureSearch.this);
                    UIUtils.openDialog(dialog);
                    if (dialog.isApproved()) {
                        TableModel<Structure> model = (TableModel<Structure>) userTable.getModel();
                        Structure structure = dialog.getStructure();
                        if (!model.getData().contains(structure)) {
                            model.addItem(structure);
                        }
                        resetText();
                    }
                }
            });
            btnRemove.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    List<Structure> selection = userTable.getSelections();
                    TableModel<Structure> model = (TableModel<Structure>) userTable.getModel();
                    for (Structure structure : selection) {
                        if (structures.contains(structure)) {
                            model.removeItem(structure);
                        }
                    }
                    resetText();
                }
            });
            toolBar.add(btnAdd);
            toolBar.add(btnRemove);
            panel.add(toolBar, BorderLayout.SOUTH);
            return panel;
        }

        private Component bottomPanel() {
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
            panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            closeButton = new JButton("გასვლა");
            panel.add(closeButton);
            closeButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                }
            });
            return panel;
        }

        private void enableComponents() {
            boolean selected = userTable.getSelection() != null;
            btnAdd.setEnabled(true);
            btnRemove.setEnabled(selected);
        }
    }

}
